package com.example.ywj.toutiao;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.ywj.toutiao.bean.News;
import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.MyNewAdapter;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.example.ywj.toutiao.utils.SpUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.myDialog.MyAlertDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class HomePageActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "HomePageActivity";
    @BindView(R.id.homePage_edit)
    public TextView homePage_edit;
    @BindView(R.id.home_page_title)
    public TextView home_page_title;
    @BindView(R.id.home_page_more)
    public TextView home_page_more;
    @BindView(R.id.home_page_fdj)
    public TextView home_page_fdj;
    @BindView(R.id.home_page_avatar)
    public ImageView home_page_avatar;
    @BindView(R.id.home_page_toutiao)
    public TextView home_page_toutiao;
    @BindView(R.id.home_page_guanzhu)
    public TextView home_page_guanzhu;
    @BindView(R.id.home_page_fensi)
    public TextView home_page_fensi;
    @BindView(R.id.home_page_huozan)
    public TextView home_page_huozan;
    @BindView(R.id.page_home_listView)
    public ListView page_home_listView;
    @BindView(R.id.home_page_back)
    public ImageView home_page_back;
    @BindView(R.id.homePage_logout)
    public TextView homePage_logout;
    @BindView(R.id.save_list_nodata)
    public LinearLayout save_list_nodata;
    public  List<News> newList = new ArrayList<>();
    public MyAlertDialog myAlertDialog;
    //public TextView home_page_toutiao;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//因为不是所有的系统都可以设置颜色的，在4.4以下就不可以。。有的说4.1，所以在设置的时候要检查一下系统版本是否是4.1以上
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.trgray));
        }
        String username = SpUtils.getString(HomePageActivity.this,"username");
        getUserInfo(username);
        initView();
        myAttentionCount(username);
        myNewCount(username);
        myFensiCount(username);
        myhuozanCount(username);
    }
    public void initView(){
        Typeface font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        homePage_edit.setOnClickListener(this);
        home_page_fdj.setTypeface(font);
        home_page_fdj.setText(getResources().getString(R.string.font5));
        home_page_more.setTypeface(font);
        home_page_more.setText(getResources().getString(R.string.font10));
        home_page_back.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        home_page_fdj.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HomePageActivity.this,SearchActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(0,0);
            }
        });
        homePage_logout.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
    }
    public void showDialog(){
        myAlertDialog = new MyAlertDialog(this).builder()
                .setTitle("确认吗？")
                .setMsg("退出登录")
                .setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SpUtils.removeString(HomePageActivity.this,"username");
                        SpUtils.putBoolean(HomePageActivity.this,"isreturn",false);
                        Intent intent = new Intent(HomePageActivity.this,MainActivity.class);
                        overridePendingTransition(0,0);
                        startActivity(intent);
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //myAlertDialog.dismiss();
                        //finish();
                    }
                });
        myAlertDialog.show();
    }
    public void getUserInfo(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.BASEURL)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getNewsByUsername(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: 123"+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code==200&&obj.has("data")){
                    JsonArray objArr = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    newList = gson.fromJson(objArr,new TypeToken<ArrayList<News>>(){}.getType());
                        News news = newList.get(0);
                        home_page_title.setText(news.getAuthor());
                        String url = Constant.BASEURL+"public/images/"+news.getAvatar()+".jpg";
                        RequestOptions requestOptions = new RequestOptions();
                        requestOptions.placeholder(R.drawable.placeholder).error(R.drawable.error_img);
                        Glide.with(HomePageActivity.this).load(url).apply(requestOptions).into(home_page_avatar);
                        page_home_listView.setVisibility(View.VISIBLE);
                        save_list_nodata.setVisibility(View.GONE);
                        MyNewAdapter myNewAdapter = new MyNewAdapter(newList);
                        page_home_listView.setAdapter(myNewAdapter);
                        page_home_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Log.i(TAG, "onItemClick: "+position);
                                Bundle bundle = new Bundle();
                                bundle.putString("id",newList.get(position).get_id());
                                bundle.putString("otherUser",newList.get(position).getUsername());
                                Intent intent = new Intent(parent.getContext(),DetailActivity.class);
                                intent.putExtras(bundle);
                                startActivity(intent);
                            }
                        });
                    }else if(code==200&&obj.has("message")){
                    page_home_listView.setVisibility(View.GONE);
                    save_list_nodata.setVisibility(View.VISIBLE);
                    getAvatar(username);
                }
                }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.homePage_edit:
                Intent intent = new Intent(HomePageActivity.this,EditActivity.class);
                startActivity(intent);
                break;
        }
    }
    public void getAvatar(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.BASEURL)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getAvatar(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //Log.i(TAG, "onResponse: 123"+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code==200){
                    String avatar = obj.get("data").getAsString();
                    String url = Constant.BASEURL+"public/images/"+avatar+".jpg";
                    RequestOptions requestOptions = new RequestOptions();
                    requestOptions.placeholder(R.drawable.placeholder).error(R.drawable.error_img);
                    Glide.with(HomePageActivity.this).load(url).apply(requestOptions).into(home_page_avatar);
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void myNewCount(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.BASEURL)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.myNewCount(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try{
                    json = response.body().string();
                }catch (Exception e){
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200){
                    Integer count = obj.get("data").getAsInt();
                    Log.i(TAG, "onResponse: "+count);
                    home_page_toutiao.setText(count+"");
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void myAttentionCount(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.BASEURL)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.myAttentionCount(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try{
                    json = response.body().string();
                }catch (Exception e){
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200){
                    Integer count = obj.get("data").getAsInt();
                    Log.i(TAG, "onResponse: "+count);
                    home_page_guanzhu.setText(count+"");
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void myFensiCount(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.BASEURL)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.myFensiCount(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try{
                    json = response.body().string();
                }catch (Exception e){
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200){
                    Integer count = obj.get("data").getAsInt();
                    Log.i(TAG, "onResponse: "+count);
                    home_page_fensi.setText(count+"");
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
    public void myhuozanCount(String username){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constant.BASEURL)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.myhuozanCount(username);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try{
                    json = response.body().string();
                }catch (Exception e){
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject)new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200){
                    Integer count = obj.get("data").getAsInt();
                    Log.i(TAG, "onResponse: "+count);
                    home_page_huozan.setText(count+"");
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t);
            }
        });
    }
}
